package com.fuluwa.domain.shared;

import org.hibernate.HibernateException;
import org.hibernate.JDBCException;
import org.hibernate.NonUniqueObjectException;
import org.hibernate.ObjectNotFoundException;
import org.hibernate.StaleObjectStateException;

import com.fuluwa.infra.exception.PersistenceException;

/**
 *	HibernateException
 *		CacheException
 *		CallbackException
 *		IdentifierGenerationException
 *		InstantiationException
 *		JDBCException
 *			ConstraintViolationException
 *			GenericJDBCException
 *			JDBCConnectionException
 *			LockAcquisitionException
 *			SQLGrammarException
 *		MappingException
 *			PropertyNotFoundException
 *		NonUniqueObjectException
 *		NonUniqueResultException
 *		PersistentObjectException
 *		PropertyAccessException
 *		PropertyValueException
 *		QueryException
 *		SerializationException
 *		StaleObjectStateException
 *		TransactionException
 *		TransientObjectException
 *		UnresolvableObjectException
 *			ObjectDeletedException
 *			ObjectNotFoundException
 *		ValidationFailure
 *		WrongClassException
 *
 * @author Saurabh S. Pawse
 * @modelguid {89DE6F67-D9B5-4F1B-A212-21C832FC6989}
 */
class HibernateExceptionTranslator {

    /** @modelguid {C8095A0F-B6B8-43DF-B6A5-1EDE155F739E} */
    public static PersistenceException translate(HibernateException he, String message) {
        String msg = null;
        PersistenceException pe = null;
        if (he instanceof JDBCException) {
            JDBCException je = (JDBCException) he;
            if (je.getErrorCode() == 1) {
                // ORA-00001

                msg = he.getMessage();
             //   return new PKDuplicationException(DASConstants.EX_CODE_GENERIC, completeMessage(msg, message), he);
            } else {
                msg = he.getMessage();
            }
        } else if (he instanceof StaleObjectStateException) {
            msg = he.getMessage();
          //  return new StaleStateException(FCRJErrorConstants.MID_ECI_FNCALL_FAIL, completeMessage(msg, message), he);
        } else if (he instanceof ObjectNotFoundException) {
            msg = he.getMessage();
         //   return new RecordNotFoundException(DASConstants.EX_CODE_GENERIC, completeMessage(msg, message), he);
        } else if (he instanceof NonUniqueObjectException) {
            msg = he.getMessage();
          //  return new NonUniqueRecordException(DASConstants.EX_CODE_GENERIC, completeMessage(msg, message), he);
        } else {
            msg = he.getMessage();
        }
        return new PersistenceException(completeMessage(msg, message),he);
    }

    public static PersistenceException translate(HibernateException he) {
        return translate(he, null);
    }

    /** @modelguid {37379951-E777-410B-98E6-BA099CCD39F0} */
    private static String completeMessage(final String msg, final String userMessage) {
        return msg + (userMessage != null ? "\n" + userMessage : "");
    }
}
